package com.rui.shangXueTang.binarySort;

/**
 * @author : [锐神NO.3]
 * @version : [v1.0]
 * @className : Node
 * @createTime : [2022/2/18 21:01]
 * @description : [二叉排序树节点]
 */

public class Node {

    public int value;

    public Node left;

    public Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    public void add(Node node){
        if(node == null){
            return;
        }
        if(node.value < this.value){
            if(this.left == null){
                this.left = node;
            }else {
                this.left.add(node);
            }
        }else {
            if(this.right == null){
                this.right = node;
            }else {
                this.right.add(node);
            }
        }
    }

    /**
     * 中序遍历,关键码字需要递增
     */
    public void infixSelect(){
        if(this.left != null){
            this.left.infixSelect();
        }
        System.out.println(this);
        if(this.right != null){
            this.right.infixSelect();
        }
    }

    /**
     * 根据关键码值查找
     * @param value 关键码值
     * @return Node
     */
    public Node selectByValue(int value){
        if(this.value == value){
            return this;
        }else if(this.value > value){
            //查左子树
            if(this.left != null){
                return this.left.selectByValue(value);
            }else {
                return null;
            }
        }else {
            //查右子树
            if(this.right != null){
                return this.right.selectByValue(value);
            }else {
                return null;
            }
        }
    }

    /**
     * 删除节点的关键码值
     * @param value 关键码值
     * @return 删除节点的父节点对象
     */
    public Node selectByParent(int value){
        if((this.left != null && this.left.value == value) || (this.right != null && this.right.value == value)){
            return this;
        }else {
            if(value < this.value && this.left != null){
                return this.left.selectByParent(value);
            }else if(value >= this.value && this.right != null){
                return this.right.selectByParent(value);
            }else {
                return null;
            }
        }
    }
}
